import Toast from 'tdesign-miniprogram/toast/index';


const basePage = require('../../../common/BasePage')
Page({
  behaviors: [basePage],
  data: {
    showCode: false,
    /**当前商品sid */
    goodsSid: [],
    statusObj: {
      999: '待提交',
      1: '待取货',
      3: '待收货',
      5: '待评价',
      7: '已完成',
      8: '退款/售后',
      6: '已取消'
    },
    pageLoading: true,
    // sendArr: ['到店自提', '同城配送', '快递配送'],
    sendArr: [{
        label: '同城配送',
        value: 1
      },
      {
        label: '快递配送',
        value: 2
      },
      {
        label: '到店自提',
        value: 3
      },
    ],
    sendIdx: 0,
    // 1待支付2已支付uu 3已全部支付 4uu费用需退款 5全部需退款 6已退款
    payArr: ['', '待支付', '已支付跑腿', '已全部支付', '跑腿需退款', '全部需退款', '已退款'],
    /**地址数据 */
    addr: {
      address: ''
    },
    /**订单类型对应的配送索引 */
    typeArr: ["", 0, 1, 2],
    order: {
      // 1-uu,2-快递，3-自提
      orderType: ''
    }, // 后台返回的原始数据

    couponArr: [],
    coupon: {},
    showCoupon: false,
    latitude: "",
    longitude: "",

    storeDetail: {},
    countDownTime: null,
    addressEditable: false,
    backRefresh: false, // 用于接收其他页面back时的状态
    formatCreateTime: '', //格式化订单创建时间
    logisticsNodes: [],
    /** 订单评论状态 */
    orderHasCommented: true,
    showRefund: false,
    reason: "",
    reasonArr: [],
  },

  onLoad(query) {
    // console.log('订单详情', query);
    this.sid = query.sid;
    this.orderType = query.orderType;
    // return console.log('query', query);
    if (query.orderType) {
      this.setData({
        sendIdx: this.data.typeArr[query.orderType] || 0
      })
      this.init();
    } else {
      this.pick_init()
    }

    this.navbar = this.selectComponent('#navbar');
    this.pullDownRefresh = this.selectComponent('#wr-pull-down-refresh');

  },

  onShow() {
    // 当从其他页面返回，并且 backRefresh 被置为 true 时，刷新数据
    if (!this.data.backRefresh) return;
    this.onRefresh();
    this.setData({
      backRefresh: false
    });
  },

  /**取货码 */
  code_click(e) {
    // return console.log("code_click", e);
    this.setData({
      showCode: true,
    })
  },
  refund_click(e) {

    this.setData({
      showRefund: true,
    })
  },
  refund_change(e) {
    this.data.reason = e.detail.value;
  },
  refund_submit() {
    this.setData({
      showRefund: false,
    })
    this.request({
      url: this.data.host + "/v1/orders/order-refund",
      data: {
        orderSid: this.sid,
        reason: this.data.reason
      },
      method: "post",
      header: {
        'content-type': 'application/x-www-form-urlencoded',
      },
      loadingTip: "取消中..."
    }, res => {

      const eventChannel = this.getOpenerEventChannel()
      eventChannel.emit('remove', {
        data: '111'
      });
      wx.navigateBack({
        delta: 1,
      })
    })
  },
  cancel_click(e) {
    // this.data.cancelUrl = "/v1/orders/cancel"

    if (this.data.reasonArr && this.data.reasonArr.length > 0) {
      this.choose_reason(this.data.reasonArr, e.currentTarget.dataset.sn, )
    } else {
      this.request({
        url: this.data.host + "/v1/orders/reason",
      }, res => {
        // console.log('reason', res);
        this.data.reasonArr = res.data;
        this.choose_reason(this.data.reasonArr, e.currentTarget.dataset.sn, )
      })
    }
  },
  choose_reason(reasonArr, sn) {
    // console.log('choose_reason', reasonArr);
    let itemList = [];
    reasonArr.map(val => {
      itemList.push(val.content)
    })
    wx.showActionSheet({
      itemList: itemList,
      alertText: '选择理由',
      // itemColor: 'itemColor',
      success: (result) => {
        // console.log('选中理由', result);
        let item = reasonArr[result.tapIndex];
        this.request({
          url: this.data.host + "/v1/orders/cancel",
          method: "post",
          data: {
            goodsOrderSn: sn,
            reasonSid: item.sid
          },
          // header: {
          //   'content-type': 'application/x-www-form-urlencoded',
          // }
        }, res => {
          wx.showToast({
            title: '取消成功',

          })
          const eventChannel = this.getOpenerEventChannel()
          eventChannel.emit('remove', {
            data: '111'
          });
          wx.navigateBack({
            delta: 1,
          })
        })
      },

    })
  },
  pick_click() {
    wx.navigateTo({
      url: '/pages/coupon/coupon-list/pick?goodsSid=' + this.data.goodsSid.join(','),
    })
  },
  coupon_change(e) {
    // console.log('选中', e.currentTarget.dataset.item);
    // this.data.coupon = e.currentTarget.dataset.item;
    this.setData({
      showCoupon: false,
      coupon: e.currentTarget.dataset.item
    })
    this.request({
      url: this.data.host + "/v1/orders/settle",
      data: {
        goodsOrderSn: this.data.order.goodsOrderSn,
        userCouponSid: e.currentTarget.dataset.item.sid
      },
      method: "post",
      loadingTip: "结算...",
      // header: {
      //   'content-type': 'application/x-www-form-urlencoded',
      // }
    }, res => {
      console.log('结算', res);
      // this.wx_pay();
      this.data.order = {
        ...this.data.order,
        ...res.data
      };
      this.setData({
        order: this.data.order
      })
    })
  },

  addr_click() {
    let that = this;
    wx.navigateTo({
      url: '/pages/usercenter/address/list/index?selectMode=1',
      events: {
        addr: function (data) {
          // console.log('addr', data)
          // that.setData({
          //   addr: data
          // })
          that.send_type(that.data.sendArr[that.data.sendIdx].value, data)
        },
      },
    })
  },
  coupon_click() {
    if (this.data.couponArr && this.data.couponArr.length > 0) {
      this.setData({
        showCoupon: true
      })
    }
    console.log('goodsSid', this.data.goodsSid);
    this.request({
      url: this.data.host + "/v1/coupons/me",
      data: {
        used: 1,
        size: 50,
        goodsId: this.data.goodsSid.join(",")
      },
      loadingTip: '加载...'
    }, res => {
      res.data.records.map(val => {
        val.reduceLimit = (val.reduceLimit / 100).toFixed(2)
      })

      this.setData({
        couponArr: res.data.records,
        showCoupon: true
      })
    })
  },
  submit_click() {
    wx.requestSubscribeMessage({
      tmplIds: ['94DOf_j_ZQ3rvVgMJEyipMA9CyH-AT6nGYNR09wzhmw'],
      success(res) {
        console.log('requestSubscribeMessage', res);
      }
    })
    if (this.data.sendIdx < 2 && !this.data.addr.address) {
      return wx.showToast({
        title: '请选择收货地址',
        icon: 'none',
      })
    }
    if (this.data.sendIdx * 1 == 0) {
      return this.wx_pay();
    }
    this.request({
      url: this.data.host + "/v1/orders/create",
      data: {
        goodsOrderSn: this.data.order.goodsOrderSn
      },
      method: "post"
    }, res => {
      wx.showToast({
        title: '提交成功',
        mask: true,
      })
      setTimeout(() => {
        wx.redirectTo({
          url: '/pages/order/list',
        })
      }, 1000);


    })
  },
  /**联系门店客服 */
  lx_store() {
    wx.openCustomerServiceChat({
      corpId: 'ww72ede85652b45a26',
      extInfo: {
        url: this.data.order.storeCustomUrl,
      },
      success: (res) => {
        console.log('打开成功', res);

        wx.reLaunch({
          url: '/pages/usercenter/index',
        })
      },
      fail: (res) => {
        console.log('打开失败', res);
        wx.showToast({
          title: '打开失败',
          icon: "error"
        })

      },

    })
  },
  lxkf_click() {
    if (!this.data.addr || !this.data.addr.sid) {
      return wx.showToast({
        title: '请选择收货地址',
        icon: 'none',
      })
    }
    this.request({
      url: this.data.host + "/v1/orders/" + this.data.addr.sid + "/customer/" + this.data.order.goodsOrderSn,

    }, res => {

      wx.openCustomerServiceChat({
        corpId: 'ww72ede85652b45a26',
        extInfo: {
          url: res.data,
        },
        success: (res) => {
          console.log('打开成功', res);
          wx.reLaunch({
            url: '/pages/usercenter/index',
          })
        },
        fail: (res) => {
          console.log('打开失败', res);
          wx.showToast({
            title: '打开失败',
            icon: "error"
          })

        },

      })
    })
  },
  wx_pay() {
    this.request({
      url: this.data.host + "/v1/pay/" + this.sid + "/wx-pay",
      data: {
        orderSid: this.sid
      },
      method: "post",
      loadingTip: "支付中..."
    }, res => {
      console.log('支付', res);
      wx.requestPayment({
        nonceStr: res.data.nonceStr,
        package: res.data.package,
        paySign: res.data.paySign,
        timeStamp: res.data.timeStamp,
        signType: res.data.signType,
        success: (res) => {
          // console.log('支付结果', res);
          setTimeout(() => {
            wx.redirectTo({
              url: '/pages/order/list',
            })
          }, 1000);
        },
        fail: (res) => {},
        complete: (res) => {},
      })
    })
  },
  send_click(e) {
    this.setData({
      sendIdx: e.currentTarget.dataset.index
    })
    this.send_type(this.data.sendArr[e.currentTarget.dataset.index].value)
  },
  onPageScroll(e) {
    this.pullDownRefresh && this.pullDownRefresh.onPageScroll(e);
  },

  onImgError(e) {
    if (e.detail) {
      console.error('img 加载失败');
    }
  },
  /**取货 */
  pick_init() {
    let that = this;
    let globalData = getApp().globalData;
    if (globalData.latitude && globalData.longitude) {
      this.data.latitude = globalData.latitude;
      this.data.longitude = globalData.longitude;
      that.pick();
    } else {
      wx.getLocation({
        altitude: true,
        highAccuracyExpireTime: 0,
        isHighAccuracy: true,
        type: "gcj02",
        success: (res) => {
          this.data.latitude = getApp().globalData.latitude = res.latitude;
          this.data.longitude = getApp().globalData.longitude = res.longitude;
          that.pick();
        },
        fail: (res) => {
          wx.showToast({
            title: '获取当前位置失败',
            icon: 'none',
          })

        },
      })
    }

  },
  // 页面初始化，会展示pageLoading
  init() {
    this.setData({
      pageLoading: true
    });
    this.request({
      url: this.data.host + "/v1/orders/" + this.sid
    }, res => {
      let arr = []
      res.data.goods.map(val => {
        val.thumb = this.get_imgUrl(val.goodsImg);
        arr.push(val.goodsId)
      })

      let addr = {
        memberName: res.data.receiveName,
        receivePhone: res.data.memberPhone,
        address: res.data.receiveAddress,
      }
      this.setData({
        pageLoading: false,
        order: res.data,
        addr: addr,
        goodsSid: arr
      });
    }, err => {
      this.setData({
        pageLoading: false
      });
    })
    // this.getStoreDetail();
    // this.getDetail()
    //   .then(() => {
    //     this.setData({ pageLoading: false });
    //   })
    //   .catch((e) => {
    //     console.error(e);
    //   });

  },
  pick() {
    this.setData({
      pageLoading: true
    });
    this.request({
      url: this.data.host + "/v1/orders/pick/" + this.sid,
      data: {
        sid: this.sid,
        latitude: this.data.latitude,
        longitude: this.data.longitude,
      },
    }, res => {
      // console.log('取货', res);
      let arr = [];
      res.data.goods.map(val => {
        val.thumb = this.get_imgUrl(val.goodsImg);
        arr.push(val.goodsId)
      })
      this.setData({
        pageLoading: false,
        order: res.data,
        goodsSid: arr
      });
      // this.send_type();
    }, err => {
      this.setData({
        pageLoading: false
      });
    })
  },
  /**选择配送方式
   * 结算类型(1-同城配送，2-快递配送，3-到店自提)	
   */
  send_type(settleType = 3, addr = "") {
    console.log("send_type", addr);
    // console.log('send_type', settleType);
    // console.log('order', this.data.order);
    let obj = {
      settleType: settleType,
      goodsOrderSn: this.data.order.goodsOrderSn,
    };
    if (settleType != 3) {
      // if (!this.data.addr.sid) {
      if (!addr || !addr.sid) {
        this.setData({
          addr: {}
        })
        return;
      }
      obj.receiveAddrSid = addr.sid

    }
    this.request({
      url: this.data.host + "/v1/orders/send-type",
      data: obj,
      method: "post"
    }, res => {
      // console.log('取货方式', res);
      this.data.order = {
        ...this.data.order,
        ...res.data
      };

      if (addr) {
        this.setData({
          order: this.data.order,
          addr: addr
        })
      } else {
        this.setData({
          order: this.data.order,

        })
      }
    })
  },
  // 页面刷新，展示下拉刷新
  onRefresh() {
    this.init();
    // 如果上一页为订单列表，通知其刷新数据
    const pages = getCurrentPages();
    const lastPage = pages[pages.length - 2];
    if (lastPage) {
      lastPage.data.backRefresh = true;
    }
  },

  // 页面刷新，展示下拉刷新
  onPullDownRefresh_(e) {
    const {
      callback
    } = e.detail;
    return this.getDetail().then(() => callback && callback());
  },


  datermineInvoiceStatus(order) {
    // 1-已开票
    // 2-未开票（可补开）
    // 3-未开票
    // 4-门店不支持开票
    return order.invoiceStatus;
  },

  // 拼接省市区
  composeAddress(order) {
    return [
        //order.logisticsVO.receiverProvince,
        order.logisticsVO.receiverCity,
        order.logisticsVO.receiverCountry,
        order.logisticsVO.receiverArea,
        order.logisticsVO.receiverAddress,
      ]
      .filter((s) => !!s)
      .join(' ');
  },



  onCountDownFinish() {
    //this.setData({ countDownTime: -1 });
    const {
      countDownTime,
      order
    } = this.data;
    if (
      countDownTime > 0 ||
      (order && order.groupInfoVo && order.groupInfoVo.residueTime > 0)
    ) {
      this.onRefresh();
    }
  },

  onGoodsCardTap(e) {
    const {
      index
    } = e.currentTarget.dataset;
    const goods = this.data.order.orderItemVOs[index];
    wx.navigateTo({
      url: `/pages/goods/details/index?spuId=${goods.spuId}`
    });
  },



  onOrderNumCopy() {
    wx.setClipboardData({
      data: this.data.order.sid,
    });
  },

  onDeliveryNumCopy() {
    wx.setClipboardData({
      data: this.data.order.logisticsVO.logisticsNo,
    });
  },

  onToInvoice() {
    wx.navigateTo({
      url: `/pages/order/invoice/index?orderNo=${this.data._order.orderNo}`,
    });
  },

  onSuppleMentInvoice() {
    wx.navigateTo({
      url: `/pages/order/receipt/index?orderNo=${this.data._order.orderNo}`,
    });
  },

  onDeliveryClick() {
    const logisticsData = {
      nodes: this.data.logisticsNodes,
      company: this.data.order.logisticsVO.logisticsCompanyName,
      logisticsNo: this.data.order.logisticsVO.logisticsNo,
      phoneNumber: this.data.order.logisticsVO.logisticsCompanyTel,
    };
    wx.navigateTo({
      url: `/pages/order/delivery-detail/index?data=${encodeURIComponent(
        JSON.stringify(logisticsData),
      )}`,
    });
  },

  /** 跳转订单评价 */
  navToCommentCreate() {
    wx.navigateTo({
      url: `/pages/order/createComment/index?orderNo=${this.orderNo}`,
    });
  },

  /** 跳转拼团详情/分享页*/
  toGrouponDetail() {
    wx.showToast({
      title: '点击了拼团'
    });
  },

  clickService() {
    Toast({
      context: this,
      selector: '#t-toast',
      message: '您点击了联系客服',
    });
  },

  onOrderInvoiceView() {
    wx.navigateTo({
      url: `/pages/order/invoice/index?orderNo=${this.orderNo}`,
    });
  },
});